#!/usr/bin/env python2
#-*- coding: utf-8 -*-


import os
import traceback

from Ump.objs.db import models
from Ump.schedule.jobs.base import JobBase
from Ump.schedule.utils import log_info_run

from Ump.objs.task.manager import TaskManager
from Ump import utils


from Ump.common import log

job_log = log.get_logger('Schedule')

     
class TaskTimeoutJob(JobBase):

    @log_info_run()
    def run(self, context):
        task_manager = TaskManager()
        tasks = models.Task.query.filter_by(is_show=True).filter_by(is_finished=False).all()

        for task in tasks:
            if not str(task.timeout).isdigit():
                continue

            timeout = int(task.timeout)
            is_timeout_now = utils.time_greater_than(task.created_at, seconds=timeout)
            job_log.warn("%s timeout, created_at:%s, timeout:%s" % (task.name, task.created_at, timeout))
            if is_timeout_now:
                error = 'task is timeout, %s' % (timeout)
                response = task_manager._timeout_response(task, error)
                task_manager.on_callback(task.uuid, response)
